import { mapMutations, mapActions, mapState } from "vuex";
import { typeClassName } from "@/pages/config/classNameMap";
import _ from "lodash";
import dayjs from "dayjs";

const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.camelCase(
      name
        .split("/")
        .pop()
        .replace(/\.\w+$/, "")
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      watchs: [],
      completeLoad: false,//验证所有元素是否全部加载完成
      me:this,
      models: {
        //模型
        productionPlan: {
          ...typeClassName["productionPlan"],
        },
        salesOrder: {
          ...typeClassName["salesOrder"],
        },
      },
      productOptions: [],
      tabName: "待提交",
      dataSet: {
        waitApprovalTableData: [],
        completeApprovalTableData: [],
        approvalFormData: {
          operateTime: "",
          action: "",
          status: "",
          opinions: "",
        },
        approvalRecords: [],
        approvalOrderData: [],
        sonPlanTableData:[],
      },
      selefFilter: {},
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.watchs.map(item=>{
      this.$watch(item.target,item.fn,{deep:item.deep})
    })
    this.$nextTick(() => {
      this.unwatch = this.$watch('vms', (newValue, oldValue) => {
        let flag = true;
        Object.keys(comp).map((k) => {
          if (!Object.keys(this.vms).includes(k)) {
            flag = false;
          }
        });
        this.completeLoad = flag;
      });
      if (process.env.NODE_ENV === "development") {
        this.init();
        console.log({ me: this, vms: this.vms, completeLoad:this.completeLoad });
      }
    });
  },
  destroyed(){
    this.unwatch();
  },
  methods: {
    init() {
      this.getProduct();
    },
    changeTabs(name) {
      console.log(name);
      this.tabName = name
      this.selefFilter.sf_status = ''
      if (name == 0) {
        this.vms.waitApprovalTable.pageNavigation.pageNumber = 1
        this.waitApprovalLoadPage(this.vms.waitApprovalTable.pageNavigation, {})
      } else {
        // this.selefFilter.sf_status = "审批中"
        this.vms.completeApprovalTable.pageNavigation.pageNumber = 1
        this.completeApprovalLoadPage(this.vms.completeApprovalTable.pageNavigation, {})
      }
    },
    waitApprovalLoadPage(pageNavigation, filter) {
      let newFilter = `className='${this.models.productionPlan.className}' && type='${this.models.productionPlan.type}'  && approveStatus in ('申请','再申请')`;

      if (typeof filter === "object" && Object.keys(filter).length > 0) {
        newFilter = newFilter + `&& approveStatus= '${filter.approveStatus}'`;
      }

      this._$queryByPage(
        this.models.productionPlan.clzs,
        pageNavigation,
        newFilter,
        "",
        "",
        false
      ).then((res) => {
        this.dataSet.waitApprovalTableData =
          this.models["productionPlan"].clzs.valueRecords;
      });
    },
    completeApprovalLoadPage(pageNavigation, filter) {
      let newFilter = `className='${this.models.productionPlan.className}' && type='${this.models.productionPlan.type}'  && approveStatus in ('退回','批准','反审退回')`;

      if (typeof filter === "object" && Object.keys(filter).length > 0) {
        newFilter = newFilter + `&& approveStatus= '${filter.approveStatus}'`;
      }

      this._$queryByPage(
        this.models.productionPlan.clzs,
        pageNavigation,
        newFilter,
        "",
        "",
        false
      ).then((res) => {
        this.dataSet.completeApprovalTableData =
          this.models["productionPlan"].clzs.valueRecords;
      });
    },
    getRecords(data) {
      let parentId = this._$getHierItemField(data.hier, "审批", "nodeId");
      this.dataSet.approvalRecords = data.hier.content.filter(
        (item) => item.parentId == parentId
      );
      this.$api.production.queryProductionPlanAndHier(data).then((res) => {
        console.log(res);
        let orderParentId = this._$getHierItemField(
          res.hier,
          "订单",
          "nodeId"
        );
        this.dataSet.approvalOrderData = res.hier.content.filter(
          (item) => item.parentId == orderParentId
        ).map(item => {
          return {
            ...item,
            ...item.values
          }
        });
        let sonPlanParentId =  this._$getHierItemField(
          res.hier,
          "子计划",
          "nodeId"
        );

        this.dataSet.sonPlanTableData =  res.hier.content.filter(
          (item) => item.parentId == sonPlanParentId
        ).map(item => {
          return {
            ...item,
            ...item.values
          }
        });
      })
    },

    /**
     * 待审批Form表单验证
     * @param {验证参数}
     */
    handleApprovalModal(row, approveStatus) {
      console.log(row);
      this.vms.approvalModal.show = true;
      this._modalShow("approvalModal")
      if (approveStatus == "批准") {
        this.dataSet.approvalFormData["action"] = "批准";
        this.dataSet.approvalFormData["status"] = "批准";
      } else if (approveStatus == "退回") {
        this.dataSet.approvalFormData["action"] = "退回";
        this.dataSet.approvalFormData["status"] = "退回";
      } else {
        this.dataSet.approvalFormData["action"] = "反审退回";
        this.dataSet.approvalFormData["status"] = "反审退回";
      }
      let now = dayjs().format("YYYY-MM-DD 00:00:00");
      this.dataSet.approvalFormData["operatorId"] = this.G_Account.userId;
      this.dataSet.approvalFormData["operatorName"] =
        "admin" || this.G_Account.userName;
      this.dataSet.approvalFormData["id"] = row.id;
      this.dataSet.approvalFormData["operateTime"] = now;
      this.getRecords(row);
    },
    approvelModalOk() {
      this.vms.approvalModal.loading = true;
      let data = this.dataSet.approvalFormData;
      let formData = {
        pointer: {
          className: this.models.productionPlan.className,
          type: this.models.productionPlan.type,
          id: data.id,
        },
        approveValues: {
          operatorId: data.operatorId,
          operatorName: data.operatorName,
          operateTime: data.operateTime,
          action: data.action,
          status: data.status,
          opinions: data.opinions,
        },
      };

      this.$api.production.approveProductionPlan(formData).then((res) => {
        console.log(res);
        this.vms.approvalModal.loading = false;
        this.vms.approvalModal.show = false;
        this.waitApprovalLoadPage(this.vms.waitApprovalTable.pageNavigation, {});
      });
    },

    getProduct() {
      let data = {
        type: "material",
        className: "MaterialDetail",
      };
      this.$api.ResourceInstance.query(data)
        .then((res) => {
          console.log(res);
          // this.dataSet.routing = res.data.data.records;
          this._$getOptions(res, "productOptions");
        })
        .catch((err) => {
          console.log(err);
        });
    },
   
  },
};
